package com.bizmda.bizsip.sink.processor;

import cn.hutool.json.JSONObject;
import com.bizmda.bizsip.common.*;
import com.bizmda.bizsip.config.AbstractSinkConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
@Slf4j
public class SinkRestController {
    private AbstractSinkConfig sinkConfig;
    private AbstractSinkProcessor sinkProcessor;

    public SinkRestController(AbstractSinkConfig sinkConfig) throws BizException {
        this.sinkConfig = sinkConfig;
        switch (sinkConfig.getProcessor()) {
            case AbstractSinkConfig.PROCESSOR_DEFAULT:
                this.sinkProcessor = new SinkProcessor(sinkConfig);
                break;
            case AbstractSinkConfig.PROCESSOR_BEAN:
                this.sinkProcessor = new BeanSinkProcessor(sinkConfig);
                break;
            case AbstractSinkConfig.PROCESSOR_SINK_BEAN:
                this.sinkProcessor = new SinkBeanSinkProcessor(sinkConfig);
                break;
            default:
                throw new BizException(BizResultEnum.SINK_TYPE_IS_ERROR);
        }
    }

    @ResponseBody
    public BizMessage<JSONObject> service(@RequestBody BizMessage<JSONObject> inMessage) {
        JSONObject outJsonObject = null;
        log.trace("Sink同步服务收到消息:\n{}", BizUtils.buildBizMessageLog(inMessage));
        if (this.sinkConfig == null || this.sinkConfig.getId() == null) {
            return BizMessage.buildFailMessage(inMessage, new BizException(BizResultEnum.SINK_SINKID_IS_NULL));
        }
        try {
            BizTools.bizMessageThreadLocal.set(inMessage);
            outJsonObject = this.sinkProcessor.process(inMessage.getData());
            return BizMessage.buildSuccessMessage(inMessage, outJsonObject);
        } catch (BizException e) {
            log.error("Sink服务调用出错",e);
            return BizMessage.buildFailMessage(inMessage, e);
        }
    }
}
